package com.ringtheweb.event;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Events class
 * @author ldewavri
 *
 */
public class Events {
	
	private static final Events instance = new Events();
	
	private Map<String,Set<Observer>> observersMap = new ConcurrentHashMap<String,Set<Observer>>();
	
	private static Log LOG = LogFactory.getLog(Events.class);
	
	
	private Events(){
		
	}
	
	public static Events instance() {
		return instance;
	}
	
	public void registerListener(String event,Observer observer) {
		Set<Observer> observers = observersMap.get(event);
		if (null == observers) {
			observers = new HashSet<Observer>();
			observersMap.put(event, observers);
		}
		observers.add(observer);
	}
	
	public void raiseEvent(String event,Object...params) {
		Set<Observer> observers = observersMap.get(event);
		if (null == observers || observers.size() == 0) {
			if (LOG.isDebugEnabled()) {
				LOG.debug(String.format("No observer for event {0}",event ));
			}
			return;
		}
		for (Observer observer : observers) {
			observer.onEvent(event, params);
		}
		
	}

}
